const fs = require('fs')

const getDescriptionCommentForOption = option =>
  option.description.trim()
    ? `
/**
 * ${option.description.trim()}
 * 
 * Official libcurl documentation: : [${option.url}](${option.url})
 */
`
    : `
/**
 * Official libcurl documentation: : [${option.url}](${option.url})
 */
`

const createConstantsFile = async ({
  constants,
  variableName,
  filePath,
  shouldGenerateCamelCaseMap = false,
  extraHeaderText = '',
}) => {
  const constantsObj = [
    `
    /**
     * @public
     */
    export interface ${variableName} {`,
    ...constants.map(
      option =>
        `
      ${getDescriptionCommentForOption(option)}readonly ${
          option.constantName
        }: "${option.constantName}",
      `,
    ),
    `}`,
  ].join('\n')

  const constantsCamelCaseMapObj = shouldGenerateCamelCaseMap
    ? [
        `export const ${variableName}CamelCaseMap = {`,
        ...constants.map(
          option =>
            `${getDescriptionCommentForOption(option)}${
              option.constantNameCamelCase
            }: "${option.constantName}",`,
        ),
        `} as const`,
      ].join('\n')
    : ''

  const optionNameUnionType = `
  /**
   * @public
   */
  export type ${variableName}Name = ${constants
    .map(option => require('util').inspect(option.constantName))
    .join(' | ')}`

  fs.writeFileSync(
    filePath,
    `/**
 * Copyright (c) Jonathan Cardoso Machado. All Rights Reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
// This file was generated by scripts/build-options.js on ${new Date().toISOString()}
// Do not edit manually
  ${extraHeaderText}
  ${constantsObj}

  ${constantsCamelCaseMapObj}

  ${optionNameUnionType}
  `,
  )
}

module.exports = {
  createConstantsFile,
  getDescriptionCommentForOption,
}
